import argparse
from engine_server.config.base import ServerConfig
from engine_server.parser.config_parser import ConfigParser
from engine_server.factory.core_factory import ServerCoreFactory
from engine_server.utils.logger import run_log


def parse_cli_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="EngineServer - Universal Inference Engine Service")
    parser.add_argument("--engine-type", required=True,
                        help="Type of inference engine (e.g. vllm)")
    parser.add_argument("--server-host", default="0.0.0.0",
                        help="EngineServer management interface host")
    parser.add_argument("--server-port", type=int, default=9001,
                        help="EngineServer management interface port")
    parser.add_argument("--config-path",
                        help="Path to engine-specific configuration file (JSON format)")
    parser.add_argument("--dp-rank", type=int, default=0,
                        help="Number of engine API server instances")
    return parser.parse_args()


def main():
    cli_args = parse_cli_args()

    server_config = ServerConfig(
        engine_type=cli_args.engine_type,
        server_host=cli_args.server_host,
        server_port=cli_args.server_port,
        config_path=cli_args.config_path,
        dp_rank=cli_args.dp_rank,
    )

    config_parser = ConfigParser(server_config=server_config)
    config = config_parser.parse()
    run_log.info(f"successfully parsed {server_config.engine_type} engine configuration")

    factory = ServerCoreFactory()
    server_core = factory.create_server_core(config=config)

    server_core.initialize()
    server_core.run()
    server_core.join()

if __name__ == "__main__":
    main()
